import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

from gd.gpsroute import makegd
from genetic_algorithm import *
from data_loader import load_data
FIXED_COLORS = [
    # 高亮颜色（替换高德相似色）
    '#9400D3',  # 深紫色
    '#FF1493',  # 深粉色（替代蓝色）
    '#32CD32',  # LimeGreen（替代绿色）
    '#DA70D6',  # 紫罗兰（替代紫色）

    # 高对比度颜色
    '#FF4500',  # 橙红色
    '#00FF00',  # 荧光绿
    '#FF69B4',  # 热粉色
    '#7FFF00',  # 黄绿色

    # 扩展颜色
    '#8A2BE2',  # 蓝紫色
    '#DC143C',  # 深红色
    '#20B2AA',  # 浅海绿
    '#FF6347',  # 番茄红
    '#BA55D3',  # 中紫色

    # 更多独特颜色
    '#00FA9A',  # 中春绿色
    '#6A5ACD',  # 石板蓝
    '#FF8C00',  # 暗橙色
    '#3CB371',  # 中海绿
    '#DAA520',  # 金色

    # 补充颜色
    '#48D1CC',  # 中绿松石
    '#C71585',  # 中紫红
    '#ADFF2F',  # 绿黄色
    '#FF00FF',  # 品红
    '#4B0082'  # 靛蓝色
]


def visualize_solution(solution, vrptwInstance):
    plt.figure(figsize=(14, 10))

    # 绘制客户点
    for c in vrptwInstance.customers[1:]:
        plt.plot(c.x, c.y, 'o', markersize=8)
        plt.text(c.x, c.y, f'{c.id}', fontsize=9, ha='center', va='bottom')

    # 绘制仓库
    depot = vrptwInstance.depot
    plt.plot(depot.x, depot.y, 's', markersize=12, color='r')

    # 绘制路径
    route_details = []
    for i, route in enumerate(solution.routes):
        color = FIXED_COLORS[i]
        route_x = [vrptwInstance.customers[n].x for n in route]
        route_y = [vrptwInstance.customers[n].y for n in route]

        plt.plot(route_x, route_y, '--', color=color, linewidth=1.5, alpha=0.8)
        for j in range(len(route) - 1):
            start = (route_x[j], route_y[j])
            end = (route_x[j + 1], route_y[j + 1])
            plt.annotate('', xy=end, xytext=start,
                         arrowprops=dict(arrowstyle="->", color=color, lw=1, alpha=0.8))

        route_details.append({
            "vehicle": i + 1,
            "customers": route[1:-1],
            "color": color
        })

    # 创建图例
    legend_elements = []
    for detail in route_details:
        legend_elements.append(Line2D([0], [0],
                                      color=detail['color'],
                                      lw=2,
                                      label=f'Vehicle {detail["vehicle"]}: {detail["customers"]}'))

    plt.legend(handles=legend_elements, loc='upper left', bbox_to_anchor=(1, 1))
    plt.title(f"VRPTW Solution (Total Cost: {solution.cost:.2f}¥)")
    plt.xlabel("X Coordinate")
    plt.ylabel("Y Coordinate")
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.show()


def main():
    instance = load_data() # 获取一个包含所有相关参数的实例对象

    ga = EnhancedGeneticAlgorithm(
        instance,
        pop_size=100, # 种群大小
        min_pop_size=50, # 最小种群大小
        max_generations=500, # 迭代次数
        crossover_rate=0.8, # 交叉概率
        mutation_rate=0.1, # 变异概率
        T=10 # 种群调整周期
    )

    best_solution, history = ga.solve()# 获取最优个体以及每代最优个体

    print("最优个体的目标函数值为：{}，所用车辆数为：{}".format(best_solution.cost, best_solution.vehicle_used))
    print("\nOptimal Solution Details:")
    print(best_solution.routes)
    # for i, route in enumerate(best_solution.routes):
    #     print(f"Vehicle {i + 1} Route: {route}")
    # # 每辆车行驶的总里程
    # for key in best_solution.routes_dissum:
    #     print(f"Vehicle {key} Route_DIS_SUM: {best_solution.routes_dissum[key]}")
    # # 时间差
    # for i, timeoff in enumerate(best_solution.route_timeoff):
    #     print(f"Vehicle {i + 1} Route: {timeoff}")

    visualize_solution(best_solution, instance)
    # makegd(best_solution.routes, "improve高德.html", 0)

if __name__ == "__main__":
    main()